package listen

import (
	"github.com/gookit/event"
	"github.com/vueadmin/global"
	"github.com/vueadmin/pkg/cache"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"time"
)

// 后台单点登录
func AdminSsoLoginListen(e event.Event) error {
	key := utils.Md5(conv.String(e.Data()["user"]))
	token := conv.String(e.Data()["token"])

	if global.CONF.Cache.Driver == "redis" {
		for k, v := range cache.Redis.HGetAll("login") {
			if v == key {
				cache.Redis.HDelete("login", k)
			}
		}
		cache.Redis.HSet("login", token, key)
	} else {
		cacheData := cache.Gocache.Getx("login")
		if cacheData == nil {
			cacheData = map[string]string{}
		}
		data := cacheData.(map[string]string)
		for k, v := range data {
			if v == key {
				delete(data, k)
			}
		}
		data[token] = key
		cache.Gocache.Setx("login", data, time.Duration(global.CONF.Adminjwt.ExpiresTime)*time.Second)
	}

	return nil
}
